<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>大文件上传</title>
  </head>
  <body>
    <input type="file" id="fileInput" />
    <button id="uploadBtn">上传</button>
    <progress id="progressBar" value="0" max="100"></progress>

    <script>
      const uploadBtn = document.getElementById("uploadBtn");
      const fileInput = document.getElementById("fileInput");
      const progressBar = document.getElementById("progressBar");

      const CHUNK_SIZE = 1 * 1024 * 1024; // 1MB

      uploadBtn.addEventListener("click", async () => {
        const file = fileInput.files[0];
        const totalChunks = Math.ceil(file.size / CHUNK_SIZE);

        for (let i = 0; i < totalChunks; i++) {
          const start = i * CHUNK_SIZE;
          const end = Math.min(start + CHUNK_SIZE, file.size);
          const chunk = file.slice(start, end);

          const formData = new FormData();
          formData.append("file", chunk);
          formData.append("chunkIndex", i);
          formData.append("totalChunks", totalChunks);
          formData.append("fileName", file.name);

          await uploadChunk(formData, i, totalChunks);
        }
      });

      function uploadChunk(formData, index, totalChunks) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.open("POST", "/upload", true);

          xhr.upload.onprogress = (event) => {
            if (event.lengthComputable) {
              const percentComplete =
                ((index + event.loaded / event.total) / totalChunks) * 100;
              progressBar.value = percentComplete;
            }
          };

          xhr.onload = () => {
            if (xhr.status === 200) {
              resolve();
            } else {
              reject(new Error("Upload failed"));
            }
          };

          xhr.send(formData);
        });
      }
    </script>
  </body>
</html>
